import { HttpService } from '@nestjs/axios'
import { Controller, Get, Query } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import { importPKCS8, SignJWT } from 'jose'
import { ApiSecurityAuth } from '~/common/decorators/swagger.decorator'

@ApiTags('Tools - 天气')
@ApiSecurityAuth()
@Controller('weather')
export class WeatherController {
  constructor(private readonly http: HttpService) { }
  @Get()
  async getWeather(@Query('city') city: string) {
    if (!city) {
      throw new Error('City parameter is required')
    }
    let authorization = ''

    const YourPrivateKey = [
      '-----BEGIN PRIVATE KEY-----',
      'MC4CAQAwBQYDK2VwBCIEIGCN8IJK10rqVJiIipeKITUJ4kdiRqZWjJmI/Z3MZXnc',
      '-----END PRIVATE KEY-----',
    ].join('\n')

    const privateKey = await importPKCS8(YourPrivateKey, 'EdDSA')
    const customHeader = {
      alg: 'EdDSA',
      kid: 'CHPN4BHYJF',
    }
    const iat = Math.floor(Date.now() / 1000) - 30
    const exp = iat + 900
    const customPayload = {
      sub: '39KVBJHAGE',
      iat,
      exp,
    }
    const token = await new SignJWT(customPayload)
      .setProtectedHeader(customHeader)
      .sign(privateKey)

    authorization = `Bearer ${token}`

    const res = await this.http.axiosRef.get(
      `https://nh33jnchyt.re.qweatherapi.com/v7/weather/now?location=${city}`,
      { headers: { Authorization: `${authorization}` } },
    )

    return res.data
  }
}
